﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
using EHTWebsiteProject.Code.BLL;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Text;
using EHTWebsiteProject.Code.Entity;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace EHTWebsiteProject.Administrator
{
    public partial class EHTMenusSubUI : System.Web.UI.Page
    {
        public Boolean IsVN = true;
        private String message = "";
        private Int32 MenuID = 0;
        private Int32 TypeMenu = 1;
        private String languageCode = "vi-VN";
        private ResourceManager rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources")); 

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                MembershipUser theUser = Membership.GetUser(Session["UserName"].ToString());
                String roleName = Roles.GetRolesForUser(theUser.UserName)[0];
                if (roleName == HangSo.ROLE_ADMIN)
                    plCheck.Visible = true;
                else
                    plCheck.Visible = false;

                try
                {
                    languageCode = Session[HangSo.LANGUAGE_CODE].ToString();
                    if (languageCode == "en-us")
                    {
                        IsVN = false;
                    }
                }
                catch (Exception ex){}
                try
                {
                    MenuID = Int32.Parse(Request.QueryString["MenuID"]);
                }
                catch{}
                try
                {
                    TypeMenu = Int32.Parse(Request.QueryString["TypeMenu"]);
                }
                catch{}
                try
                {
                    message = Request.QueryString["Message"].ToString();
                    if(message!="")
                        ltrErorr.Text = HelpMethod.ApplySuccess(message);
                }
                catch{}
                fixPathFileUpload(TypeMenu);               

                if (IsVN == true)
                    this.ddlListPage.Items.Insert(0, new ListItem(HangSo.DanhMuc, "0"));
                else
                    this.ddlListPage.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "0"));

                if (MenuID != 0)
                {
                    if (IsVN == true)
                        lbAdd_Edit.Text = HangSo.Edit_VN;
                    else
                        lbAdd_Edit.Text = HangSo.Edit_Other;
                    Menus theMenus = MenusProvider.GetMenusByID(MenuID);
                    txtMenuNameOther.Text = theMenus.MenuNameOther;
                    txtMenuNameVN.Text = theMenus.MenuNameVN;
                    txtThuTu.Text = theMenus.MenuOrder.ToString();
                    ddlDanhMucMenu.SelectedValue = theMenus.ID.ToString();
                    if (theMenus.ControlUrl !="#")
                        ddlListPage.SelectedValue = theMenus.ControlUrl.ToString();
                    else
                        ddlListPage.SelectedValue = "0";
                    if(theMenus.ParentID!=0)
                        ddlMenuCha.SelectedValue = theMenus.ParentID.ToString();
                    ViewState["action"] = HangSo.ACTION_UPDATE;
                    ViewState["ID"] = MenuID;
                    ViewState["Url"] = theMenus.ControlUrl;
                    ViewState["IconTrangThai"] = theMenus.IconTrangThai;
                    ViewState["MenuLevel"] = theMenus.MenuLevel;
                    ViewState["Icon"] = theMenus.Icon;
                    try
                    {
                        ddlListPage.SelectedValue = theMenus.ControlUrl.ToString();
                    }
                    catch
                    {
                        ddlListPage.SelectedValue = "-1";
                    }

                }
                else
                {
                    ViewState["action"] = HangSo.ACTION_ADD;
                    if (IsVN == true)
                        lbAdd_Edit.Text = HangSo.Add_VN;
                    else
                        lbAdd_Edit.Text = HangSo.Add_Other;
                }

                Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
                LoadLanguage(Thread.CurrentThread.CurrentCulture);                

                LoadDanhMucMenu();
                LoadMenuCha();

                ddlDanhMucMenu.Enabled = false;
                ddlDanhMucMenu.SelectedValue = Session["ID"].ToString();
                
            }
        }
        /// <summary>
        /// Ham load ngon ngu
        /// </summary>
        /// <param name="ci"></param>
        public void LoadLanguage(CultureInfo ci)
        {
            lbSave.Text = rm.GetString("lbSave", ci);
            lbApply.Text = rm.GetString("lbApply", ci);           
            lbHelp.Text = rm.GetString("lbHelp", ci);
            lbMenuSub.Text = rm.GetString("lbMenuSub", ci);
            lbMenuNameVN.Text = rm.GetString("lbMenuNameVN", ci);
            lbMenuNameOther.Text = rm.GetString("lbMenuNameOther", ci);
            lbDanhMucMenu.Text = rm.GetString("lbDanhMucMenu", ci);
            lbParent.Text = rm.GetString("lbParent", ci);
            lbThuTu.Text = rm.GetString("lbThuTu", ci);
            lbTypeMenu.Text = rm.GetString("lbTypeMenu", ci);
            lbCancel.Text = rm.GetString("lbCancel",ci);
            
        }

        public void LoadDanhMucMenu()
        {

            ddlDanhMucMenu.DataSource = DanhMucMenusProvider.GetDanhMucMenus(TypeMenu);
            ddlDanhMucMenu.DataTextField = "TitleOrder";
            ddlDanhMucMenu.DataValueField = "ID";
            ddlDanhMucMenu.DataBind();
            if (IsVN == true)
            {
                ddlDanhMucMenu.Items.Insert(0, new ListItem(HangSo.DanhMuc, "-1"));
            }
            else
            {
                ddlDanhMucMenu.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "-1"));
            }
        }

        public void LoadMenuCha()
        {
            MembershipUser theUser = Membership.GetUser(Session["UserName"].ToString());
            String roleName = Roles.GetRolesForUser(theUser.UserName)[0];
            if (roleName == HangSo.ROLE_ADMIN)
            {
                Int32 Type = Int32.Parse(Session["ID"].ToString());
                if (Type==1)
                    ddlMenuCha.DataSource = MenusProvider.GetMenusByLevel(1);
                if (Type == 4)
                {
                    ddlMenuCha.DataSource = MenusProvider.GetMenusByLevel(4);
                    ddlMenuCha.Enabled = false;
                }
                if(Type == 6)
                    ddlMenuCha.DataSource = MenusProvider.GetMenusByLevel(6);
            }
            else
                ddlMenuCha.DataSource = MenusProvider.GetMenusByLevel(6);
            
            if (IsVN == true)
            {
                ddlMenuCha.DataTextField = "MenuNameVN";
                ddlMenuCha.DataValueField = "MenuID";
                ddlMenuCha.DataBind();
                ddlMenuCha.Items.Insert(0, new ListItem(HangSo.DanhMuc, "0"));
            }
            else
            {
                ddlMenuCha.DataTextField = "MenuNameOther";
                ddlMenuCha.DataValueField = "MenuID";
                ddlMenuCha.DataBind();
                ddlMenuCha.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "0"));
            }
            
        }

        /// <summary>
        /// Ham kiem tra du lieu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public Boolean ValidateData()
        {
            Boolean flag = true;

            if (txtMenuNameOther.Text == "")
            {
                if (IsVN == true)
                    message = HangSo.check_VN;
                else
                    message = HangSo.check_Other;
                flag = false;
            }

            if (txtMenuNameVN.Text == "")
            {
                if (IsVN == true)
                    message = HangSo.check_VN;
                else
                    message = HangSo.check_Other;
                flag = false;
            }

            if (ddlDanhMucMenu.SelectedValue =="-1")
            {
                if (IsVN == true)
                    message = HangSo.meagessddl;
                else
                    message = HangSo.meagessddlOther;
                flag = false;
            }
           
            

            return flag;
        }

        protected void ImgSave_Click(object sender, ImageClickEventArgs e)
        {
            String action = ViewState["action"].ToString();
            Int32 MenuIDOut = -1;
            if (ValidateData() == false)
            {
                ltrErorr.Text = HelpMethod.ErorrLogin(message);
                return;
            }
            else
            {
                Menus theMenus = new Menus();
                theMenus.MenuOrder = Int32.Parse(txtThuTu.Text);
                theMenus.MenuNameVN = txtMenuNameVN.Text;
                theMenus.MenuNameOther = txtMenuNameOther.Text;
                theMenus.ID = Int32.Parse(ddlDanhMucMenu.SelectedValue.ToString());
                theMenus.Icon = UpLoadFile();
                if (ddlMenuCha.SelectedValue == "0")
                {
                    theMenus.MenuLevel = 1;
                    theMenus.ParentID = 0;                    
                }
                if (ddlMenuCha.SelectedValue != "0")
                {
                    theMenus.MenuLevel = 2;
                    theMenus.ParentID = Int32.Parse(ddlMenuCha.SelectedValue);
                }

                if (action == HangSo.ACTION_ADD)
                {
                    theMenus.MenuID = -1;
                    theMenus.IconTrangThai = "~//images//tick.png";
                    if(ddlListPage.SelectedValue=="0")
                        theMenus.ControlUrl = "#";  
                    else
                        theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();  

                    MenuIDOut = MenusProvider.UIMenus(theMenus, true);
                }
                else
                {
                    theMenus.MenuID = Int32.Parse(ViewState["ID"].ToString());
                    theMenus.IconTrangThai = ViewState["IconTrangThai"].ToString();
                    theMenus.MenuLevel = Int32.Parse(ViewState["MenuLevel"].ToString());
                    if(ddlListPage.SelectedValue=="0")
                        theMenus.ControlUrl = "#";  
                    else
                        theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();                           

                    MenuIDOut = MenusProvider.UIMenus(theMenus, false);
                }
                Response.Redirect("EHTMenusSub.aspx");
            }
        }

        protected void ImgApply_Click(object sender, ImageClickEventArgs e)
        {
            String action = ViewState["action"].ToString();
            Int32 MenuIDOut = -1;
            if (ValidateData() == false)
            {
                ltrErorr.Text = HelpMethod.ErorrLogin(message);
                return;
            }
            else
            {
                Menus theMenus = new Menus();
                theMenus.MenuOrder = Int32.Parse(txtThuTu.Text);
                theMenus.MenuNameVN = txtMenuNameVN.Text;
                theMenus.MenuNameOther = txtMenuNameOther.Text;
                theMenus.ID = Int32.Parse(ddlDanhMucMenu.SelectedValue.ToString());
                theMenus.Icon = UpLoadFile();

                if (ddlMenuCha.SelectedValue == "0")
                {
                    theMenus.MenuLevel = 1;
                    theMenus.ParentID = 0;
                }
                

                if (action == HangSo.ACTION_ADD)
                {
                    theMenus.MenuID = -1;
                    theMenus.IconTrangThai = "~//images//tick.png";
                    theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();                    

                    MenuIDOut = MenusProvider.UIMenus(theMenus, true);
                }
                else
                {
                    theMenus.MenuID = Int32.Parse(ViewState["ID"].ToString());
                    theMenus.IconTrangThai = ViewState["IconTrangThai"].ToString();
                    theMenus.MenuLevel = Int32.Parse(ViewState["MenuLevel"].ToString());
                    theMenus.ControlUrl =  ddlListPage.SelectedValue.ToString();                        
                    MenuIDOut = MenusProvider.UIMenus(theMenus, false);
                }
                String str = "";
                if (IsVN == true)
                    str = HangSo.App_VN;
                else
                    str = HangSo.App_Other;
                Response.Redirect("EHTMenusSubUI.aspx?MenuID=" + MenuIDOut.ToString() + "&&Message=" + str);
            }
        }

        /// <summary>
        /// Hàm fix đường dẫn Url của danh muc trang index
        /// </summary>
        public void fixPathFileUpload(Int32 TypeMenu)
        {
            if (TypeMenu == 1)
            {
                ArrayList arrAdmin = new ArrayList();
                DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/Administrator"));
                foreach (FileInfo file in dirInfo.GetFiles("*.aspx"))
                {
                    arrAdmin.Add(new Item("~//Administrator//" + file.Name.ToString(), "~//Administrator//" + file.Name.ToString()));                    
                }
                ddlListPage.DataSource = arrAdmin;
                ddlListPage.DataTextField = "Ten1";
                ddlListPage.DataValueField = "Code1";
                ddlListPage.DataBind();
            }
            else
            {
                ArrayList arrIndex = new ArrayList();
                DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/"));
                foreach (FileInfo file in dirInfo.GetFiles("*.aspx"))
                {
                    arrIndex.Add(new Item(file.Name.ToString(),file.Name.ToString()));
                }
                ddlListPage.DataSource = arrIndex;
                ddlListPage.DataTextField = "Ten1";
                ddlListPage.DataValueField = "Code1";
                ddlListPage.DataBind();
            }
            
                      
        }

        /// <summary>
        /// Ham upload file len server
        /// </summary>
        /// <returns></returns>
        public String UpLoadFile()
        {
            String UploadFile = "";

            String action = ViewState["action"].ToString();
            if (this.fulIcon.HasFile)
            {
                String fileName = fulIcon.PostedFile.FileName;
                String pathAvatars = Server.MapPath("~/");
                String fileType = Path.GetExtension(fileName);
                String FileNewName = DateTime.Now.Ticks.ToString() + fileType;
                try
                {
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulIcon.PostedFile.InputStream);
                    if (Int32.Parse(oImg.Width.ToString()) > 50)
                    {


                        int thumbWidth = 50;
                        int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oThumbNail.Save(pathAvatars + "\\ImageDatas\\Icons\\" + FileNewName);
                        oImg.Dispose();
                    }

                    else
                    {

                        this.fulIcon.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Icons//" + FileNewName);
                    }
                    ImgIcon.ImageUrl = "~\\ImageDatas\\Icons\\" + FileNewName;
                    UploadFile = FileNewName;
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    UploadFile = ViewState["Icon"].ToString();
                }
                else
                {
                    if (radAdmin.Checked)                    
                        UploadFile = "icon-16-category.png";                       
                    else if(radSystem.Checked)
                        UploadFile = "icon-48-category.png";
                    else
                        UploadFile = "icon-16-category.png";       
                }
            }

            return UploadFile;
        }
        
    }
}